package cn.memorynine.consumer.service;

import cn.hutool.core.bean.BeanUtil;
import cn.memorynine.common.model.ResponseWrapper;
import cn.memorynine.consumer.model.consumer.logup.IsAccountExistParam;
import cn.memorynine.consumer.model.consumer.logup.IsAccountExistResult;
import cn.memorynine.consumer.model.consumer.logup.LogupParam;
import cn.memorynine.dao.entity.Consumer;
import cn.memorynine.dao.entity.ShopCart;
import cn.memorynine.dao.mapper.ConsumerMapper;
import cn.memorynine.dao.mapper.ShopCartMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ConsumerLogupService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private ShopCartMapper shopCartMapper;

    /**
     * 1.用户注册
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper logup(LogupParam param){
        Consumer consumer = new Consumer();
        BeanUtil.copyProperties(param,consumer);
        consumer.setPoints(0);
        consumer.setStateId(10);
        consumer.setSex(true);
        //注册的均为普通用户
        consumer.setStatusId(20);
        if (param.getEmail() != null){
            //邮箱注册
            consumer.setName(param.getEmail());
        } else if (param.getPhone() != null){
            //手机号注册
            consumer.setName(param.getPhone());
        }
        consumerMapper.insert(consumer);
        //为用户创建一个购物车
        ShopCart shopCart = new ShopCart();
        shopCart.setConsumerAid(consumer.getAid());
        shopCartMapper.insert(shopCart);

        return ResponseWrapper.markSuccess();
    }

    /**
     * 2.查看当前手机号/邮箱是否被注册
     */
    public ResponseWrapper isAccountExist(IsAccountExistParam param){

        IsAccountExistResult isAccountExistResult = new IsAccountExistResult();

        List<Consumer> consumers = new ArrayList<>();

        if (param.getEmail() != null){
            //邮箱查询
            consumers = consumerMapper.selectList(
                    Wrappers.<Consumer>lambdaQuery()
                            .eq(Consumer::getEmail, param.getEmail())
            );
        } else if (param.getPhone() != null){
            //手机号查询
            consumers = consumerMapper.selectList(
                    Wrappers.<Consumer>lambdaQuery()
                            .eq(Consumer::getPhone, param.getPhone())
            );
        }
        isAccountExistResult.setIsExist(consumers.isEmpty()?false:true);
        return ResponseWrapper.markSuccess(isAccountExistResult);
    }
}
